package fun.shuofeng.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 朔风
 * @date 2024-01-25 16:11
 */
public class LSaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "A1").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "B1").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "C1").start();
    }
}

class Ticket {
    /**
     * 票数
     */
    private int number = 30;

    private final ReentrantLock lock = new ReentrantLock();

    public void sale() {
        // 上锁
        lock.lock();
        try {
            // 判断是否有票
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + number-- + "张票，剩余 " + number + "张票");
            }
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}
